/**
 * Copyright (c) 2018, Alex. All rights reserved.
 */
package com.oschina.bottle.poi;

import com.oschina.bottle.utils.BeanMapUtils;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * fileInfo构建工具
 *
 * @author <a href="mailto:zhongchao@gegejia.com">zhong</a>
 * @version 1.0 2018/1/26
 * @since 1.0
 */
public class FileInfoBuilder {

    /**
     * 生成导出文件的FileInfo
     *
     * @param fileName          文件名
     * @param outputStream      输出流
     * @param data              数据
     * @return  FileInfo
     */
    public static <T> FileInfo buildExport(String fileName, OutputStream outputStream, List<T> data) {
        FileInfo fileInfo = new FileInfo();
        fileInfo.setName(fileName);

        if(data == null || data.size() == 0) {
            return fileInfo;
        }

        fileInfo.setHeads(getHead(data.get(0).getClass()));
        fileInfo.setData(BeanMapUtils.parseMap(data));
        fileInfo.setOutput(outputStream);
        return fileInfo;
    }


    /**
     * 生成导入文件的FileInfo
     *
     * @param fileName      文件名
     * @param inputStream   输入流
     * @param targetClass   用来存放最终数据的对象类
     * @return  fileInfo
     */
    public static FileInfo buildImport(String fileName, InputStream inputStream, Class<?> targetClass) {
        FileInfo fileInfo = new FileInfo();

        fileInfo.setName(fileName);
        fileInfo.setHeads(getHead(targetClass));
        fileInfo.setInput(inputStream);
        return fileInfo;
    }


    private static List<Head> getHead(Class<?> targetClass) {

        Field[] fields = targetClass.getDeclaredFields();

        List<Head> heads = new ArrayList<>(fields.length);
        for(Field field : fields) {
            Header header = field.getAnnotation(Header.class);
            if(header != null) {
                Head head = new Head();
                head.setFieldName(field.getName());
                head.setColumnName(header.name());
                head.setIndex(header.index());
                head.setFieldClass(field.getType());
                heads.add(head);
            }
        }

        return heads;
    }
}
